package com.lxk.service.impl;

import com.lxk.dao.AsMyMapper;
import com.lxk.dao.AuctionMapper;
import com.lxk.dao.GoodsMapper;
import com.lxk.pojo.Auction;
import com.lxk.pojo.AuctionExample;
import com.lxk.service.AuctionService;
import com.lxk.util.exception.GlobalException;
import com.lxk.vo.AuctionModel;
import com.lxk.vo.AuctionShowModel;
import com.lxk.vo.PageModel;
import com.lxk.vo.result.CodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class AuctionServiceImpl implements AuctionService {

	@Autowired
	private AuctionMapper am;
	@Autowired
	private AsMyMapper mm;
	@Autowired
	private GoodsMapper gm;
	
	public Integer setAuction(Auction auction) {
		int ins = am.insertSelective(auction);
		if(ins == 0) {
			throw new GlobalException(CodeMsg.MYSQL_CRUD_FAIL);
		}
		return auction.getAuctionId();
	}

	public Integer getTotalPages(Integer num) {
		AuctionExample example = new AuctionExample();
		Integer count = (int)am.countByExample(example);
		Integer totalPages = count%num==0 ? count/num : count/num+1;
		return totalPages;
	}

	public PageModel<AuctionModel> selAuctionPage(Integer pageIndex, Integer num, Integer totalPages, Integer sort, Integer order) {
		int start = (pageIndex-1)*num;
		List<AuctionModel> list = mm.selAuctionPage(start, num, sort, order);
		PageModel<AuctionModel> model = new PageModel<AuctionModel>();
		model.setList(list);
		model.setNum(num);
		model.setPageIndex(pageIndex);
		model.setTotalPages(totalPages);
		return model;
	}

	public List<Auction> selAuctionByGoodsId(Integer goodsId) {
		AuctionExample example = new AuctionExample();
		AuctionExample.Criteria criteria = example.createCriteria();
		criteria.andGoodsIdEqualTo(goodsId);
		List<Auction> auctionList = am.selectByExample(example);
		return auctionList;
	}

	public void updateAuction(Auction auction) {
		am.updateByPrimaryKeySelective(auction);
	}

	public AuctionShowModel showAuctionGoodsInfo() {
		AuctionShowModel model = mm.selAuctionShowModel();
		if(model==null) {
			return null;
		}else{
			Date beginTime = model.getAuctionBeginTime();
			Date nowTime = new Date();
			if(beginTime.before(nowTime)) {
				model.setIsStarted(1);
			}else {
				model.setIsStarted(0);
			}
			if(model.getIsFinished()==0) {
				Date endTime = model.getAuctionEndTime();
				if(endTime.before(nowTime)) {
					model.setIsFinished(1);
				}
			}
		}
		return model;
	}

}
